/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import dao.UserDAO;
import entities.User;
import game.Table;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.icefaces.application.PushRenderer;
import other.Costants;

/**
 *
 * @author alessandro
 */
@ManagedBean
@SessionScoped
public class UserManager implements Serializable {

    private String username;
    private String password;
    private User user;
    private String state;

    /*tavolo*/
    private int bots;
    private boolean logged = false;
    private String errorMessage = null;
    @ManagedProperty(value = "#{tablesManager}")
    private TablesManager tablesManager;
    @ManagedProperty(value = "#{chatUserBean}")
    private ChatUserBean chatUserBean;

    /* registrazione */
    private String errorMessageR;
    private String registerUsername;
    private String registerPassword;
    private String registerPasswordC;

    public ChatUserBean getChatUserBean() {
        return chatUserBean;
    }
    public String getErrorMessageR() {
        return errorMessageR;
    }
    public void setErrorMessageR(String errorMessageR) {
        this.errorMessageR = errorMessageR;
    }
    public String getRegisterPassword() {
        return registerPassword;
    }
    public void setRegisterPassword(String registerPassword) {
        this.registerPassword = registerPassword;
    }
    public String getRegisterPasswordC() {
        return registerPasswordC;
    }
    public void setRegisterPasswordC(String registerPasswordC) {
        this.registerPasswordC = registerPasswordC;
    }
    public String getRegisterUsername() {
        return registerUsername;
    }
    public void setRegisterUsername(String registerUsername) {
        this.registerUsername = registerUsername;
    }
    public int getBots() {
        return bots;
    }
    public void setBots(int bots) {
        this.bots = bots;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public void setChatUserBean(ChatUserBean chatUserBean) {
        this.chatUserBean = chatUserBean;
    }
    public String getErrorMessage() {
        return errorMessage;
    }
    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public boolean isLogged() {
        return logged;
    }
    public void setLogged(boolean logged) {
        this.logged = logged;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public TablesManager getTablesManager() {
        return tablesManager;
    }
    public void setTablesManager(TablesManager tablesManager) {
        this.tablesManager = tablesManager;
    }

    public String register() {
        String returnPage = Costants.REGISTER;

        if(registerPassword.equals(registerPasswordC)) {
            User userL = UserDAO.findUserByUsername(registerUsername);
            if(userL == null){
                if(!(registerUsername.substring(0, 3).contains(Costants.BOTNAME))) {
                userL = new User();
                userL.setAdmin(0);
                userL.setPassword(registerPassword);
                userL.setUser(registerUsername);
                userL.setPunti(0);
                boolean flag = UserDAO.newUser(userL);
                if(flag) {
                    errorMessageR = Costants.OK_REGISTER;
                } else {
                    errorMessageR = Costants.ERROR_PROBLEM_REGISTER;
                }
                } else {
                    errorMessageR = Costants.ERROR_NAME_BOT;
                }
            } else {
                errorMessageR = Costants.ERROR_USER_EXIST;
            }

        } else {
            errorMessageR = Costants.ERROR_WRONG_PASSWORD_C;
        }


        return returnPage;
    }

    /*procedura di login*/
    public String login() {
        User userT = UserDAO.findUser(username, password);
        if (userT != null) {
            logged = true;
            this.user = userT;
            errorMessage = null;
            state = Costants.CHATTING;
            return Costants.CHAT;
        } else {
            errorMessage = "User or password wrong. Please try again";
            return Costants.LOGIN;
        }

    }
    public boolean isLoggedIn() {
        return logged;
    }
    /* procedura di logout*/
    public String logout() {
        PushRenderer.removeCurrentView(Costants.PUSH_GROUP);
        PushRenderer.removeCurrentView(Costants.PUSH_TABLE);
        chatUserBean.removeFromList(username);
        tablesManager.leaveTable(username);
        logged = false;
        errorMessage = null;
        errorMessageR = "";
        registerUsername = "";
        registerPassword = "";
        registerPasswordC = "";
        user = null;
        state = Costants.CHATTING;
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            ExternalContext ec = context.getExternalContext();
            ec.redirect("home.xhtml");
        } catch (Exception e) {
        }
        if(this.tableExist()) {
            tablesManager.leaveTable(username);
        }
        return Costants.HOME;
    }

    public boolean isChatting() {
        boolean flag = false;
        if (state.equals(Costants.CHATTING)) {
            flag = true;
        }

        return flag;
    }

    public boolean isWatching() {
        boolean flag = false;
        if (state.equals(Costants.WATCHING)) {
            flag = true;
        }

        return flag;
    }

    public boolean isWaiting() {
        boolean flag = false;
        if (state.equals(Costants.WAITING)) {
            flag = true;
        }

        return flag;
    }

    public void joinTable(String table) {
        PushRenderer.removeCurrentView(Costants.PUSH_GROUP);
        tablesManager.addWatcher(username, table);
        state = Costants.WATCHING;
        PushRenderer.render(Costants.PUSH_GROUP);

    }

    public boolean tableExist() {
        boolean flag = false;
        if (tablesManager.getTableByUser(username) != null) {
            flag = true;
        }

        return flag;
    }

    public void setPoints(ArrayList<String> winners) {
        for (int i = 0; i < winners.size(); i++) {
            String name = winners.get(i);
            System.out.println("Aggiungo i punti a " + name);
            if(name.startsWith(Costants.BOTNAME)) {
                name = Costants.BOTNAME;
            }
            User userT = UserDAO.findUserByUsername(name);
            if (userT != null) {
                userT.setPunti(userT.getPunti() + (Costants.WINNER_POINTS/winners.size()));
            }
            if(UserDAO.update(userT)) {
                System.out.println("Punti aggiornati per " + userT.getUser());
            } else {
                System.out.println("Punti non aggiornati per " + userT.getUser());
            }
        }
    }

    public void removePoints(ArrayList<String> loosers) {
        for (int i = 0; i < loosers.size(); i++) {
            String name = loosers.get(i);
            System.out.println("Tolgo i punti a " + name);
            if(name.startsWith(Costants.BOTNAME)) {
                name = Costants.BOTNAME;
            }
            User userT = UserDAO.findUserByUsername(name);
            if (userT != null) {
                userT.setPunti(userT.getPunti() + Costants.LOSER_POINTS);
            }
            if(UserDAO.update(userT)) {
                System.out.println("Punti aggiornati per " + userT.getUser());
            } else {
                System.out.println("Punti non aggiornati per " + userT.getUser());
            }
        }
    }
}
